package com.david.buffer;

import android.Manifest;
import android.hardware.usb.UsbDevice;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.david.buffer.usb.USBMonitor;

import java.io.DataOutputStream;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    static {
        System.loadLibrary("tinyalsa");
    }

    private USBMonitor usbMonitor;

    private StringBuilder usbSb = new StringBuilder();
    private StringBuilder contentSb = new StringBuilder();
    private TextView contentTv;
    private TextView usbTv;

    private int PERMISSION_REQUEST_CODE = 1024;
    private ReadBuffer buffer;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        contentTv = findViewById(R.id.contentTv);
        usbTv = findViewById(R.id.usbTv);

        requestPermissions(new String[] {Manifest.permission.CAMERA, Manifest.permission.RECORD_AUDIO,
                        Manifest.permission.CAPTURE_AUDIO_OUTPUT, Manifest.permission.MODIFY_AUDIO_SETTINGS},
                PERMISSION_REQUEST_CODE);

        buffer = new ReadBuffer(new ReadBuffer.OnReadBufferCallback() {
            @Override
            public void onLog(String msg) {
                contentSb.append(msg).append("\n");
                contentTv.post(new Runnable() {
                    @Override
                    public void run() {
                        contentTv.setText(contentSb.toString());
                    }
                });

            }
        });
        usbMonitor = new USBMonitor(this, onDeviceConnectListener);

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        usbMonitor.register();

    }

    private final USBMonitor.OnDeviceConnectListener onDeviceConnectListener = new USBMonitor.OnDeviceConnectListener() {
        @Override
        public void onAttach(UsbDevice device) {
            usbSb.append("onAttach").append("\n");
            usbMonitor.requestPermission(device);
            setContent();
        }

        @Override
        public void onDettach(UsbDevice device) {
            usbSb.append("onDettach").append("\n");
            setContent();
        }

        @Override
        public void onConnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock, boolean createNew) {
            usbSb.append("onConnect").append("\n");
            setContent();
        }

        @Override
        public void onDisconnect(UsbDevice device, USBMonitor.UsbControlBlock ctrlBlock) {
            usbSb.append("onDisconnect").append("\n");
            setContent();
        }

        @Override
        public void onCancel(UsbDevice device) {
            usbSb.append("onCancel").append("\n");
            setContent();
        }
    };

    private void setContent() {
        usbTv.post(new Runnable() {
            @Override
            public void run() {
                usbTv.setText(usbSb.toString());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        usbMonitor.unregister();
    }

    public void startRecord(View v) {
        Log.e("ReadBuffer", "========>");
        buffer.readBuffer(1, 0, 2, 48000, 0, 1000, 1);
    }

    private boolean rootCommand(String command) {
        Process process = null;
        DataOutputStream os = null;
        try {
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(command + "\n");
            os.writeBytes("exit\n");
            os.flush();
            process.waitFor();
        } catch (Exception e) {
            Log.d("*** DEBUG ***", "ROOT REE" + e.getMessage());
            return false;
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                process.destroy();
            } catch (Exception e) {
                // nothing
            }
        }

        Log.d("*** DEBUG ***", "Root SUC ");
        return true;

    }
}